console.log("sw-tips.js");

// 该扩展程序会提取所有提示，随机选择一个，然后将其保存到存储空间。我们会创建一个每天触发一次的闹钟，以更新提示。关闭 Chrome 后，系统不会保存闹钟。因此，我们需要检查闹钟是否存在，如果不存在，则创建一个。
// Fetch tip & save in storage
const updateTip = async () => {
    const response = await fetch('https://chrome.dev/f/extension_tips');
    const tips = await response.json();
    const randomIndex = Math.floor(Math.random() * tips.length);
    return chrome.storage.local.set({ tip: tips[randomIndex] });
};

const ALARM_NAME = 'tip';

// Check if alarm exists to avoid resetting the timer.
// The alarm might be removed when the browser session restarts.
async function createAlarm() {
    const alarm = await chrome.alarms.get(ALARM_NAME);
    if (typeof alarm === 'undefined') {
        chrome.alarms.create(ALARM_NAME, {
            delayInMinutes: 1,
            periodInMinutes: 1440
        });
        updateTip();
    }
}

createAlarm();

// Update tip once a day
chrome.alarms.onAlarm.addListener(updateTip);

// Send tip to content script via messaging
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.greeting === 'tip') {
        chrome.storage.local.get('tip').then(sendResponse);
        return true;
    }
});